﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PersonalExpenseTracker.PersistenceLayer;

namespace PersonalExpenseTracker
{
    public partial class ExpenseListUserControl : UserControl
    {
        public ExpenseListUserControl()
        {
            InitializeComponent();
        }

        private void lnkCurrentMonth_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BindListView(PersistenceLayerFacade.GetThisMonthExpenses());
        }

        private void lnkCurrentYear_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BindListView(PersistenceLayerFacade.GetThisYearExpenses());
        }

        private void lnkAllExpenses_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BindListView(PersistenceLayerFacade.GetAllExpenses());
        }

        private void BindListView(List<Expense> expenses)
        {
            this.Cursor = Cursors.WaitCursor;
            lstExpenses.SuspendLayout();
            this.SuspendLayout();

            lstExpenses.Items.Clear();
            foreach (Expense exp in expenses)
            {
                // date, category, amount, expense id, category id, description
                ListViewItem item = new ListViewItem();
                item.Tag = exp.ExpenseId;
                item.Text = exp.Date.ToString("dd/MM/yyyy hh:mm");
                item.SubItems.Add(exp.CategoryName);
                item.SubItems.Add(exp.Amount.ToString());
                item.SubItems.Add(exp.Description);
                lstExpenses.Items.Add(item);
            }
            lstExpenses.ResizeColumns();
            lstExpenses.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();
            this.Cursor = Cursors.Default;
        }

        private void ExpenseListUserControl_Load(object sender, EventArgs e)
        {
            lnkCurrentMonth_LinkClicked(sender, null);
        }

        private void lstExpenses_DoubleClick(object sender, EventArgs e)
        {
            if (lstExpenses.SelectedItems.Count > 0)
            {
                ((ExpenseTracker)this.ParentForm).EditExpense(
                    PersistenceLayerFacade.GetExpenseById(
                        (int)lstExpenses.SelectedItems[0].Tag));
            }
        }
    }
}
